package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.dto.order.SundayOrderDto;
import org.itboys.mobile.service.mysql.mobile.SundayMobileOrderService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.MobileSignUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年2月9日
 * 联系方式 ：empty90911@126.com
 * 描述：农厨_订单_controller。
 *
 */
@Controller
@RequestMapping("/tianjie/mobile/finance/globe/product")
public class SundayMobileOrderController extends BaseController {
    @Autowired
    private SundayMobileOrderService orderService;


    @RequestMapping(value="/createOrder",method= {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value="【全球购-订单】创建订单。")
    public void createOrder(HttpServletRequest request,
             HttpServletResponse response,
                @ApiParam(required = true, name = "cartIds", value = "购物车ID集合(非商品ID)") @RequestParam(value = "cartIds", required = true) List<Long> cartIds,
                @ApiParam(required = false, name = "addressId", value = "收货地址Id。") @RequestParam(value="addressId",required=false) Long addressId,
                @ApiParam(required = false, name = "remark", value = "订单备注。") @RequestParam(value="remark",required=false) String remark,
                @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{

            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            StringBuilder cartIdsStr=new StringBuilder();
            for(Long cartId:cartIds){
                cartIdsStr.append(cartId+",");
            }
            param.put("cartIds",cartIdsStr.substring(0,cartIdsStr.length()-1).toString());//实际是字符串。cartIds=1,2,3
            param.put("remark",remark);
            param.put("nonce", nonce);

           /* boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/

            Long memberId = AccountIdHoldUtils.getMemberId();
            Map<String,Object> result = orderService.createOrder(memberId,cartIds,addressId,remark);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.info("/tianjie/mobile/finance/globe/product/order/createOrder-------"+e);
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/getOrder",method= {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value="【全球购-订单】获取订单。分页")
    public void getOrder(HttpServletRequest request,
                            HttpServletResponse response,
                            @ApiParam(required = true, name = "orderStatus", value = "订单状态." +
                            "0全部，1，待付款，2待配送，3配送中，4待评价，5已评价，6待退款， 7已退款，8待退货，9已退货,10已取消") @RequestParam(value="orderStatus",required=true) Integer orderStatus,
                            @ApiParam(required = false, name = "createTime_start", value = "查询参数。开始时间。默认为空") @RequestParam(value = "createTime_start", required = false) String createTime_start,
                            @ApiParam(required = false, name = "createTime_end", value = "查询参数。结束时间。默认为空") @RequestParam(value = "createTime_end", required = false) String createTime_end,

                            @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                            @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                            @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
                            @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
                            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayOrderDto> result=orderService.getOrder(request,memberId,orderStatus);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.info("/tianjie/mobile/finance/globe/product/order/getOrder-------"+e);
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    @RequestMapping(value="/confirmReceive",method= {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value="【全球购-订单】确认收货。分页")
    public void confirmReceive(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                       @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {

        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
           if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.confirmReceive(orderId,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;

            }else{
                logger.info("/tianjie/mobile/finance/globe/product/order/confirmReceive-------"+e);
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

}
